/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.quangtin3.sb;

import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.quangtin3.entity.CollectedValue;
import org.quangtin3.entity.CollectionColumn;
import org.quangtin3.entity.User;

/**
 *
 * @author Quang
 */
@Stateless
public class CollectedValueFacade extends AbstractFacade<CollectedValue> {

    @PersistenceContext(unitName = XSC_PU_NAME)
    private EntityManager em;
    @Resource
    private javax.transaction.UserTransaction utx;
    private static final Logger LOGGER = Logger.getLogger(CollectedValueFacade.class.getName());

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CollectedValueFacade() {
        super(CollectedValue.class);
    }

    public CollectedValue find(CollectionColumn column, User user) {
        Query query = getEntityManager().createNamedQuery("CollectedValue.findByCollectionColumnAndUser");
        query.setParameter("column", column.getId());
        query.setParameter("user", user.getId());

        CollectedValue cv;
        try {
            cv = (CollectedValue) query.getSingleResult();
        } catch (NoResultException e) {
            cv = new CollectedValue(user.getId(), column.getId());
        }

        return cv;
    }

    public void save(List<CollectedValue> values) {
        try {
            utx.begin();
            for (CollectedValue cv : values) {
                em.persist(cv);
            }
            utx.commit();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Saving list of collected value error", e);
            throw new RuntimeException(e);
        }
    }
}
